<?php

namespace rainlee\authn\provider;

use think\helper\Str;

class ModelUserProvider
{

    protected $config;


    public function __construct($config)
    {
        $this->config = $config;
    }

    /**
     * 获取主键名
     *
     * @return 
     */
    public function getPk()
    {
        $model = $this->createModel();
        return $model->getPk();
    }

    /**
     * 根据ID获取用户数据
     *
     * @return 
     */
    public function retrieveById($id)
    {
        $model = $this->createModel();
        return $model->getUserInfo([$this->getPk() => $id]);
    }

    /**
     * 通过用户主键和remember token获取用户
     * 
     * @param int $id
     * @param string $token
     * 
     * @return
     */
    public function retrieveByRememberToken($id, $token)
    {
        $model = $this->createModel();

        $user = $model->getUserInfo([$model->getPk() => $id, 'remember_token' => $token]);

        if (!$user) {
            return;
        }

        return $user;
    }

    /**
     * 根据账号密码等参数获取用户
     * 
     * @param $credentials
     */
    public function retrieveByCredentials($credentials)
    {
        if (
            empty($credentials) ||
            (count($credentials) === 1 && array_key_exists('password', $credentials))
        ) {
            return;
        }

        $where = [];
        foreach ($credentials as $key => $value) {
            if (!Str::contains($key, 'password')) {
                $where[$key] = $value;
            }
        }
        $model = $this->createModel();

        return $model->getUserInfo($where);
    }

    /**
     * 验证用户密码是否正确
     * 
     * @param
     */
    public function validatePassword($user, $password)
    {
        if (isset($this->config['validate_pass']) && $this->config['validate_pass'] == 'md5') {
            return hash_equals($user->password, md5($password));
        }
        return password_verify($password, $user->password);
    }

    /**
     * 更新Remember Token
     * 
     * @param \think\model $user
     * @param string $toekn
     * @return void
     */
    public function updateRememberToken($user, $token)
    {
        $user->remember_token = $token;
        $user->save();
    }

    /**
     * 创建模型实例
     *
     * @return \think\Model
     */
    protected function createModel()
    {
        $class = '\\' . ltrim($this->config['model'], '\\');

        return new $class;
    }
}
